﻿from PySide6.QtCore import Qt
from ui.components.base.base_dialog import TgBaseDialog
from ui.components.layouts.vbox_layout import TgVBoxLayout
from ui.components.layouts.hbox_layout import TgHBoxLayout
from ui.components.buttons.button import TgButton
from ui.components.composite.table import TgTable
from ui.components.dialogs.file_dialog import TgFileDialog


class BacktestRecordsDialog(TgBaseDialog):
    """
    通用回测记录查看对话框。
    通过传入列配置和行数据，渲染为表格并支持导出CSV。
    columns: List[Dict] with keys: 'key', 'title'
    rows: List[Dict]
    """

    def __init__(self, title: str, columns: list[dict], rows: list[dict] | None = None, parent=None):
        self._title = title
        self._columns = columns or []
        self._rows = rows or []
        super().__init__(parent)
        self.setWindowTitle(title)
        self.resize(1100, 600)

    def setup_ui(self):
        main_layout = TgVBoxLayout(self)

        self.table = TgTable(editable=False, font_size='small', highlight_on_selection=False)
        self._refresh_table()
        main_layout.addWidget(self.table)

        btn_layout = TgHBoxLayout()
        btn_layout.addStretch()
        self.export_btn = TgButton("导出CSV", theme="secondary")
        self.close_btn = TgButton("关闭", theme="primary")
        self.export_btn.clicked.connect(self._export_csv)
        self.close_btn.clicked.connect(self.accept)
        btn_layout.addWidget(self.export_btn)
        btn_layout.addWidget(self.close_btn)
        main_layout.addLayout(btn_layout)

    def set_rows(self, rows: list[dict]):
        self._rows = rows or []
        self._refresh_table()

    def _refresh_table(self):
        headers = [c.get('title', c.get('key', '')) for c in self._columns]
        data = []
        for r in self._rows:
            row = []
            for c in self._columns:
                key = c.get('key')
                val = r.get(key, '') if isinstance(r, dict) else ''
                row.append('' if val is None else str(val))
            data.append(row)
        self.table.set_data(headers, data)
        self.table.enable_sorting(True)
        self.table.set_column_resize_mode('interactive', stretch_last=True, auto_resize_content=True)

    def _export_csv(self):
        try:
            dialog = TgFileDialog(self)
            file_path = dialog.get_save_file_name(title=f"保存{self._title}", extensions=["csv"], default_name=f"{self._title}.csv")
            if not file_path:
                return
            tw = self.table.table_widget
            rows = tw.rowCount()
            cols = tw.columnCount()
            headers = []
            for c in range(cols):
                h = tw.horizontalHeaderItem(c)
                headers.append(h.text() if h else f"Column_{c}")
            import csv
            with open(file_path, 'w', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerow(headers)
                for r in range(rows):
                    row_data = []
                    for c in range(cols):
                        item = tw.item(r, c)
                        row_data.append(item.text() if item else '')
                    writer.writerow(row_data)
        except Exception:
            # 静默失败，避免打断主流程
            pass
